package com.bookcycle.panda.webfront.controller;


import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.security.token.SSOToken;
import com.bookcycle.panda.webfront.constant.URLConstant;
import com.bookcycle.panda.webfront.doo.AccountDO;
import com.bookcycle.panda.webfront.doo.UserDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.bookcycle.panda.webfront.constant.URLConstant.URL_GET_USER_BY_ID;


/**
 * @author Mason
 * @date 2018/3/27
 */
@Controller
public class AccountController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String LOGIN_SUCCESS="登录成功";
    private final String REGISTER_SUCCESS="注册成功";
    private final String UPDATE_SUCCESS="修改成功";
    private final String USER_SERVICE_ERROR="用户服务器错误";
    private final String BAD_PARAM="账号、密码不符合要求";
    private final String ACCOUNT_EXIST="账号已经存在";
    private final String ACCOUNT_NOT_EXIST="账号不存在";
    private final String ERROR_UNKNOWN="未知错误";
    private final String PASSWORD_NOT_EQUAL="密码不一致";
    private final String NO_AUTHORITY="没有权限";
    
    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        SSOHelper.clearLogin(request,response);
        request.getSession().invalidate();
        return redirectTo("home");
    }
    
    /**
     * 跳转登录页面
     * @return
     */
    @Login(action = Action.Skip)
    @RequestMapping("/signIn")
    public String signIn(){
        return "sign-in";
    }

    /**
     * 登录
     * @param identifier
     * @param password
     * @param type
     * @return
     */
    @Login(action = Action.Skip)
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestParam("identifier")String identifier,
                        @RequestParam("password")String password,
                        @RequestParam("type")int type,
                        Model model){
        RestTemplate restTemplate=new RestTemplate();
        MultiValueMap multiValueMap=new LinkedMultiValueMap();
        multiValueMap.add("identifier",identifier);
        multiValueMap.add("password",password);
        multiValueMap.add("type",type);
        String accountId;
        SSOToken ssoToken=SSOToken.create();
        try{
            ResponseEntity<AccountDO> responseEntity=restTemplate.postForEntity(URLConstant.URL_GET_ACCOUNT,multiValueMap,AccountDO.class);
            accountId=responseEntity.getBody().getId();
            logger.info("IP:"+request.getHeader("X-Real-IP")+","+identifier+",登录成功");
        }catch (HttpClientErrorException e){
            logger.info("IP:"+request.getRemoteUser()+",登录失败");
           return redirectTo("error");
        }

        /**刚注册的账号可能无用户信息*/
        multiValueMap.add("accountId",accountId);
        try {
            ResponseEntity<UserDO> responseEntity1=restTemplate.postForEntity(URLConstant.URL_GET_USER,multiValueMap,UserDO.class);
            ssoToken.setId(responseEntity1.getBody().getId());
            SSOHelper.setCookie(request,response,ssoToken,true);
            return redirectTo("home");
        }catch (HttpClientErrorException e){
            if(e.getStatusCode()==HttpStatus.NOT_FOUND){
                UserDO userDO=new UserDO();
                userDO.setAccountId(accountId);
                userDO.setAvatar("/");
                userDO.setAddress("/");
                userDO.setBirthday(new Date());
                userDO.setNickname("/");
                userDO.setSex(true);
                multiValueMap.add("user",userDO);
                restTemplate.postForEntity(URLConstant.URL_SAVE_USER,multiValueMap,Void.class);
                ResponseEntity<UserDO> responseEntity1=restTemplate.postForEntity(URLConstant.URL_GET_USER,multiValueMap,UserDO.class);
                ssoToken.setId(responseEntity1.getBody().getId());
                SSOHelper.setCookie(request,response,ssoToken,true);
                return redirectTo("home");
            }else {
                return redirectTo("error");
            }
        }
    }

    /**
     * 跳转注册页面
     * @return
     */
    @RequestMapping("/signUp")
    public String signUp(){
        return "sign-up";
    }

    /**
     *
     * @param identifier
     * @param password
     * @param passwordConfirm
     * @param type
     * @return
     */
    @RequestMapping(value = "register",method = RequestMethod.POST)
    @ResponseBody
    public String register(@RequestParam("identifier")String identifier,
                           @RequestParam("password")String password,
                           @RequestParam("passwordConfirm")String passwordConfirm,
                           @RequestParam("type") int type){
        if(!password.equals(passwordConfirm)){
            return this.PASSWORD_NOT_EQUAL;
        }
        RestTemplate restTemplate=new RestTemplate();
        MultiValueMap<String,Object> multiValueMap=new LinkedMultiValueMap<>();
        multiValueMap.add("identifier",identifier);
        multiValueMap.add("password",password);
        multiValueMap.add("type",type);

        try {
            ResponseEntity<Void> responseEntity=restTemplate.postForEntity(URLConstant.URL_SAVE_ACCOUNT,multiValueMap,Void.class);
            if(responseEntity.getStatusCode()== HttpStatus.CREATED){
                return this.REGISTER_SUCCESS;
            }else {
                return this.ERROR_UNKNOWN;
            }
        }catch (HttpClientErrorException e){
            HttpStatus httpStatus=e.getStatusCode();
            if(HttpStatus.NOT_ACCEPTABLE == httpStatus){
                return this.BAD_PARAM;
            }else if(HttpStatus.CONFLICT == httpStatus){
                return this.ACCOUNT_EXIST;
            }else if(HttpStatus.INTERNAL_SERVER_ERROR == httpStatus){
                return this.USER_SERVICE_ERROR;
            }else {
                return this.ERROR_UNKNOWN;
            }
        }
    }

    /**
     * 跳转注册页面
     * @return
     */
    @RequestMapping("/showAccount")
    public String showAccount(Model model){
        String userId=SSOHelper.getSSOToken(request).getId();
        RestTemplate restTemplate=new RestTemplate();
        MultiValueMap multiValueMap=new LinkedMultiValueMap();
        multiValueMap.add("userId",userId);
        ResponseEntity<UserDO> responseEntity=restTemplate.postForEntity(URLConstant.URL_GET_USER_BY_ID,multiValueMap,UserDO.class);
        String accountId=responseEntity.getBody().getAccountId();
        multiValueMap.add("id",accountId);
        ResponseEntity<AccountDO> responseEntity1=restTemplate.postForEntity(URLConstant.GET_ACCOUNT_BY_ID,multiValueMap,AccountDO.class);
        String telephone=responseEntity1.getBody().getTelephone();
        telephone=telephone.substring(0,3)+"****"+telephone.substring(8,11);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String registerTime=sdf.format(responseEntity1.getBody().getRegisterTime());
        model.addAttribute("registerTime",registerTime);
        model.addAttribute("telephone",telephone);
        return "account";

    }

    /**
     * 绑定手机号
     * @return
     */
    @RequestMapping(value = "/bindPhone",method = RequestMethod.POST)
    public String bindPhone(@RequestParam("telephone") String telephone){
        String userId=SSOHelper.getSSOToken(request).getId();
        RestTemplate restTemplate=new RestTemplate();
        MultiValueMap multiValueMap=new LinkedMultiValueMap();
        multiValueMap.add("userId",userId);
        ResponseEntity<UserDO> responseEntity=restTemplate.postForEntity(URLConstant.URL_GET_USER_BY_ID,multiValueMap,UserDO.class);
        String accountId=responseEntity.getBody().getAccountId();
        multiValueMap.add("id",accountId);
        ResponseEntity<AccountDO> responseEntity1=restTemplate.postForEntity(URLConstant.GET_ACCOUNT_BY_ID,multiValueMap,AccountDO.class);
        AccountDO accountDO=responseEntity1.getBody();
        accountDO.setTelephone(telephone);
        multiValueMap.add("account",accountDO);
        restTemplate.postForEntity(URLConstant.UPDATE_ACCOUNT,multiValueMap,Void.class);
        return redirectTo("showAccount");
    }



}
